package comum;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class PacoteFile {

	static public void sendFile(Socket socket, String path) {
		try {
			
			ObjectOutputStream oops;
			oops = new ObjectOutputStream(socket.getOutputStream());
			FileTransfer transfer = getFileTransfer(path);
			
			oops.writeObject(transfer); 
			oops.flush();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	static protected FileTransfer getFileTransfer(String path) {
		
		File myFile = new File(path);

		FileTransfer transfer = new FileTransfer();
		transfer.mybytearray = new byte[(int)myFile.length()];
		try {
			FileInputStream fis = new FileInputStream(myFile);
			BufferedInputStream bis = new BufferedInputStream(fis);

			bis.read(transfer.mybytearray, 0, transfer.mybytearray.length);
		}
		catch(Exception e) {
			System.out.println("DEU RUIM.");
		}
		return transfer;
	}
	
	static public void receiveFile(Socket socket, String path) {
		try {
			
			ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
			FileTransfer filetransfer = (FileTransfer) ois.readObject();
			
			FileOutputStream fos = new FileOutputStream(path);
			BufferedOutputStream bos = new BufferedOutputStream(fos);
			bos.write(filetransfer.mybytearray, 0 , filetransfer.mybytearray.length);
			bos.flush();
			bos.close();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
}
